package cn.flying.cloud.gateway.route.service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import cn.flying.cloud.base.common.exception.BizException;
import cn.flying.cloud.base.common.utils.lang.SnowflakeUtil;
import cn.flying.cloud.base.common.vo.PageResponse;
import cn.flying.cloud.gateway.route.model.GatewayRoute;
import cn.flying.cloud.gateway.route.repository.GatewayRouteRepository;

/**
 * @author: admin
 * @date: 2024年05月08日 17:24
 * @version: 1.0
 */
@Service
public class GatewayRouteService {

    @Resource
    private GatewayRouteRepository gatewayRouteRepository;

    /**
     * 分页查询路由配置
     *
     * @param page
     * @param size
     * @param route
     * @return
     */
    public PageResponse page(Integer page, Integer size, GatewayRoute route) {
        Specification<GatewayRoute> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtils.hasText(route.getRouteId())) {
                predicates.add(criteriaBuilder.like(root.get("routeId"), "%" + route.getRouteId() + "%"));
            }
            if (StringUtils.hasText(route.getRouteName())) {
                predicates.add(criteriaBuilder.like(root.get("routeName"), "%" + route.getRouteName() + "%"));
            }
            if (StringUtils.hasText(route.getStatus())) {
                predicates.add(criteriaBuilder.equal(root.get("status"), route.getStatus()));
            }
            predicates.add(criteriaBuilder.equal(root.get("deleted"), "0"));
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        Page<GatewayRoute> routes = gatewayRouteRepository.findAll(specification, PageRequest.of(page - 1, size));

        return new PageResponse(routes.getTotalElements(), page, routes.getContent());
    }

    /**
     * 查询所有
     *
     * @return
     */
    public List<GatewayRoute> findAll() {
        Specification<GatewayRoute> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("status"), "Y"));
            predicates.add(criteriaBuilder.equal(root.get("deleted"), "0"));
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        List<GatewayRoute> routes = gatewayRouteRepository.findAll(specification, Sort.by(Sort.Direction.ASC, "seq"));
        return routes;
    }

    /**
     * 保存路由配置
     *
     * @param route
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(GatewayRoute route) {
        if (route.getId() == null) {
            route.setId(SnowflakeUtil.nextId());
        }
        route.setCreatedBy("admin");
        route.setCreatedTime(LocalDateTime.now());
        route.setUpdatedBy("admin");
        route.setUpdatedTime(LocalDateTime.now());
        route.setDeleted("0");
        route.setRevision("0");
        gatewayRouteRepository.save(route);
    }

    /**
     * 更新路由配置
     *
     * @param route
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(GatewayRoute route) {
        route.setCreatedBy("admin");
        route.setCreatedTime(LocalDateTime.now());
        route.setUpdatedBy("admin");
        route.setUpdatedTime(LocalDateTime.now());
        route.setDeleted("0");
        route.setRevision("0");
        gatewayRouteRepository.save(route);
    }

    /**
     * 删除路由配置
     *
     * @param route
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(GatewayRoute route) {
        Optional<GatewayRoute> optional = gatewayRouteRepository.findById(route.getId());
        if (!optional.isPresent()) {
            throw new BizException("路由不存在");
        }
        GatewayRoute gatewayRoute = optional.get();
        gatewayRoute.setCreatedBy("admin");
        gatewayRoute.setCreatedTime(LocalDateTime.now());
        gatewayRoute.setUpdatedBy("admin");
        gatewayRoute.setUpdatedTime(LocalDateTime.now());
        gatewayRoute.setDeleted("1");
        gatewayRoute.setRevision("0");
        gatewayRouteRepository.save(gatewayRoute);
    }


}
